<template>
  <div class="login">
    <div class="container">
      <h2>登录</h2>
      <p>还没有账号? <span style="color: #1e5eff"><a href="/register">点击注册</a></span></p>

      <lbFormVue
        labelWidth="100"
        :ruleForm="userForm"
        :formData="formData"
        :rules="UserRules"
        ruleFormRef="ruleFormRef"
        SubmitText="登录"
      >
        <template v-slot:username>
          <el-input
            placeholder="输入图书账号"
            class="input-with-select"
            v-model="userForm.username"
          >
            <template #prepend> <el-button :icon="User" /> </template
          ></el-input>
        </template>
        <template v-slot:password>
          <div style="width: 100%; height: 3vh; text-align: left">
            <el-input
              placeholder="输入图书密码"
              class="input-with-select"
              v-model="userForm.password"
              show-password
            >
              <template #prepend> <el-button :icon="Lock" /> </template
            ></el-input>
          </div>
        </template>
        <template v-slot:login>
          <div style="width: 70%; height: 5vh; text-align: left">
            <el-checkbox v-model="remember" label="记住密码" size="large" />
          </div>
          <div style="width: 100%; height: 2vh; text-align: left">
            <el-button class="elButton" type="primary" @click="Login"
              >登录账号</el-button
            >
          </div>
        </template>
        <template v-slot:rememeber> </template>
      </lbFormVue>
      <p style="color: #1e5eff; text-align: center; margin: 0">忘记密码?</p>
      <el-divider style="width: 70%; margin: 3vh auto" />
      <p>或使用以下方式登录</p>
      <img src="../assets/vx.png" width="30" style="margin-top: 1vh" />
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref } from "vue";
import DataCheck from "../util/CheckUtil";
import { Lock, User } from "@element-plus/icons-vue";
import lbFormVue from "../components/form/lb-form.vue";
import VailDataForm from "../util/VaildateForm";
import VailDataError from "../util/LbError";
import { ElLoading,ElMessage } from "element-plus";
import { useStore } from "vuex";
import {useRouter} from 'vue-router'
import Api from "../api";
const userForm = reactive({
  username: "",
  password: "",
});
const router = useRouter();
const store = useStore();
const remember = ref(false);
const ruleFormRef = ref();
const formData = [
  {
    label: "",
    prop: "username",
    remark: "username",
    flag: true,
  },
  {
    label: "",
    prop: "password",
    remark: "password",
    flag: true,
  },

  {
    remark: "login",
    flag: false,
  },
  {
    remark: "rememeber",
    flag: false,
  },
];
const flag = reactive([]);
function Reg(value) {
  var reg = /^[a-zA-Z0-9_]{6,}$/;
  return reg.test(value);
}
const userVaildator = (rule, value, callback) => {
  if (value === "") {
    callback(new VailDataError("", flag[0]));
  } else if (!Reg(value)) {
    callback(new VailDataError("请输入只含数字字母且大于6位", flag[0]));
  } else {
    flag[0] = true;
    if (userForm.username !== "") {
      if (!ruleFormRef.value) return;
      ruleFormRef.value.validateField("username", () => null);
    }
    callback();
  }
};
const passVaildator = (rule, value, callback) => {
  if (value === "") {
    callback(new VailDataError("", flag[1]));
  } else {
    flag[1] = true;
    if (userForm.password !== "") {
      if (!ruleFormRef.value) return;
      ruleFormRef.value.validateField("password", () => null);
    }
    callback();
  }
};
const UserRules = reactive({
  username: [{ validator: userVaildator, trigger: "blur" }],
  password: [{ validator: passVaildator, trigger: "blur" }],
});

const RememberUser = (username, password) => {
  let user = {
    username: username,
    password: password,
  };
  localStorage.setItem("user", window.btoa(JSON.stringify(user)));
};
onMounted(() => {
  let user = localStorage.getItem("user");
  if (user !== null) {
    let arr = JSON.parse(window.atob(user));
    if (arr !== null || arr !== "") {
      userForm.username = arr.username;
      userForm.password = arr.password;
    }
  }
});
const Login = async() => {
  const loading = ElLoading.service({
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0.7)",
  });
  if (DataCheck(userForm, flag)) {
    store.dispatch("Login", userForm);
    await new Promise((resolve)=>{
      setTimeout(()=>{
      let isLogin = computed(() => store.getters["isLogin"]);
      if(JSON.stringify(isLogin.value) === "{}"){
        ElMessage.error('网络波动,重新登录')
      }
    if (remember.value) {
      RememberUser(userForm.username, userForm.password);
    }
    switch(isLogin.value.code){
      case 200 : 
        ElMessage.success('登录成功');
        router.push(Api.ROUTELIST.USERINFO);
        break;
      case 413 : 
        ElMessage.error('账号或密码错误'); 
        break;
      case 420 : 
        ElMessage.error('账号被冻结,请联系管理员');
        break;
    }
    loading.close();
    resolve();
    },1000)
  })
  } else {
    loading.close();
    return false;
  }
};
</script>

<style scoped>
.login {
  width: 100%;
  height: 100vh;
  background-color: rgb(222, 232, 255);
  display: flex;
  justify-content: center;
  align-items: center;
}
.container {
  width: 30%;
  height: 60vh;
  background-color: #fff;
  text-align: center;
}
h2 {
  text-align: center;
}
.container p {
  text-align: center;
  color: #5a607f;
  font-size: 13px;
}
.container input {
  outline: none;
}
.input-with-select .el-input-group__prepend {
  background-color: var(--el-fill-color-blank);
}
.container .el-input {
  width: 70%;
  /* margin-left: -5%; */
  margin-top: 1vh;
}
.elButton {
  width: 70%;
  background-color: #1e5eff;
}
img {
  cursor: pointer;
}
a{
    text-decoration: none;
    color: #1e5eff;
}
</style>